package libs

import (
	"github.com/olivere/elastic"
	"os"
	"log"
	"context"
	"discuz/models"
)

const ELASTIC_URL = "http://localhost:9200"

func Esclient() (client *elastic.Client,err error) {
	file := "./elastic.log"
	//s := elastic.SearchHits{}
	logFile,_ := os.OpenFile(file,os.O_RDWR|os.O_CREATE|os.O_APPEND,0777)
	cfg := []elastic.ClientOptionFunc{
		elastic.SetURL(ELASTIC_URL),
		elastic.SetSniff(false),
		elastic.SetInfoLog(log.New(logFile, "ES-INFO: ", 0)),
		elastic.SetTraceLog(log.New(logFile, "ES-TRACE: ", 0)),
		elastic.SetErrorLog(log.New(logFile, "ES-ERROR: ", 0)),
	}
	client,err = elastic.NewClient(cfg...)
	if err != nil{
		log.Println(err)
	}
	return
}

func ElaIsExists(eindex,etype string,eid string) bool {
	client,_ := Esclient()
	exist,_ := client.Exists().
		Index(eindex).
		Type(etype).
		Id(eid).
		Do(context.Background())
	if !exist{
		log.Println("Id未找到",eid)
		return false
	}
	return true
}

func AddElaWeChat(doc *models.WeChat) (id string){
	client ,_:= Esclient()
	defer client.Stop()
	//if !ElaIsExists("wechat","user",id){
	//	return
	//}
	res,_ := client.Index().Index("wechat").Type("msg").BodyJson(doc).Do(context.Background())
	return res.Id
}

func BulkAdd(docs []models.WeChat){
	client ,_:= Esclient()
	bulkRequest := client.Bulk()
	defer client.Stop()
	for _,doc := range docs{
		esRequest := elastic.NewBulkIndexRequest().Index("test").Doc(doc)
		bulkRequest = bulkRequest.Add(esRequest)
	}
	bulkRequest.Do(context.Background())
}